package main

// Dictionary is a map from string to string
type Dictionary map[string]string

const (
	// ErrNotFound is used for 404
	ErrNotFound = DictionaryErr("could not find the word you were looking for")

	// ErrWordExists is used for exists element
	ErrWordExists = DictionaryErr("cannot add word because it already exists")

	// ErrWordDoesNotExist used for update
	ErrWordDoesNotExist = DictionaryErr("cannot update word because it does not exist")
)

// DictionaryErr is used for simplify the errors
type DictionaryErr string

func (e DictionaryErr) Error() string {
	return string(e)
}

// Search in a map
func (d Dictionary) Search(word string) (string, error) {
	definition, ok := d[word]
	if !ok {
		return "", ErrNotFound
	}

	return definition, nil
}

// Add an element to the map
func (d Dictionary) Add(word, definition string) error {
	_, err := d.Search(word)

	switch err {
	case ErrNotFound:
		d[word] = definition
	case nil:
		return ErrWordExists
	default:
		return err
	}

	return nil
}

// Update the exists element with a new value
func (d Dictionary) Update(word, definition string) error {
	_, err := d.Search(word)

	switch err {
	case ErrNotFound:
		return ErrWordDoesNotExist
	case nil:
		d[word] = definition
	default:
		return err
	}

	return nil
}

// Delete the element in the map
func (d Dictionary) Delete(word string) {
	// Go 的 map 有一个内置函数 delete。它需要两个参数。第一个是这个 map，第二个是要删除的键。
	delete(d, word)
}
